import time

from fastapi import APIRouter
from pydantic import BaseModel, EmailStr
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig, MessageType

from config import config
router = APIRouter()

qq_mail_config = ConnectionConfig(
    MAIL_USERNAME=config.MAIL_USERNAME,
    MAIL_PASSWORD=config.MAIL_PASSWORD,
    MAIL_FROM=config.MAIL_FROM,
    MAIL_SERVER=config.MAIL_SERVER,
    MAIL_PORT=587,
    MAIL_SSL_TLS=False,
    MAIL_STARTTLS=True,
    USE_CREDENTIALS=True,
    VALIDATE_CERTS=True,
)
SEND_EMAIL_TO = config.SEND_EMAIL_TO


class Email(BaseModel):
    address: list[EmailStr]


@router.post('/send_email')
async def send_email(email: Email):
    start_time = time.time()

    body_html = ''' 
  <h1>This is email from Fastapi-Mail</h1> 
  <p>Fastapi send mail successfully</p>
  '''

    message = MessageSchema(
        subject="Fastapi email",
        recipients=[SEND_EMAIL_TO],
        body=body_html,
        subtype=MessageType.html
    )

    fm = FastMail(qq_mail_config)
    try:
        await fm.send_message(message)
    except Exception as e:
        print("Error: ", e)
    finally:
        await fm.close()

    return {'time': round((time.time()-start_time)*1000)}
